#include "rtconfig.h"
#include "rtthread.h"
#include <rtdevice.h>
#include "finsh.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

#define MAX_DATA_SIZE 256

static void at24test(int argc, char **args)
{
    int offset = 0;
    if(argc > 1)
        offset = atoi(args[1]);

   rt_device_t dev = rt_device_find("eeprom");
   if(dev == NULL)
   {
        printf("Invalid i2c0 bus device\r\n");
        return;
   }

   uint8_t data[MAX_DATA_SIZE] = {0};
   uint8_t rddata[MAX_DATA_SIZE] = {0};

   for(int i=0; i<MAX_DATA_SIZE; i++)
   {
        data[i] = i;
   }

   if(rt_device_open(dev, RT_DEVICE_OFLAG_RDWR) != RT_EOK)
   {
        printf("Open eeprom device failed!\r\n");
        return;
   }

   int ret = rt_device_write(dev, offset, data, MAX_DATA_SIZE - offset);
   if(ret == MAX_DATA_SIZE - offset)
   {
        ret = rt_device_read(dev, offset, rddata, MAX_DATA_SIZE - offset);
        if(ret == MAX_DATA_SIZE - offset)
        {
            printf("Read %d data: ", ret);
            if(memcmp(rddata, data, MAX_DATA_SIZE - offset) == 0)
            {
                printf("Compare Right!!!\r\n");
            }
            else
            {
                printf("Compare Wrong!!!\r\n");
            }
            
            for(int i=0; i<MAX_DATA_SIZE - offset; i++)
            {
                printf("%02X ", rddata[i]);
            }
            printf("\r\n");
        }
        else
        {
            printf("Read data failed:%d\r\n", ret);
        }
   }
   else
   {
        printf("Write data failed:%d\r\n", ret);
   }

   rt_device_close(dev);
}


MSH_CMD_EXPORT_ALIAS(at24test, at24test, This is a at24cxx test!);
